package com.morihacky.android.rxjava;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import com.morihacky.android.rxjava.retrofititchen.MyServerInterface;

import java.io.IOException;

import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class RetorfitActivity extends AppCompatActivity {


	private TextView textView_info;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_retorfit);

		ButterKnife.bind(this);

		initView();

		//initRetorfit();
		initRetorfit2();

	}

	private void initRetorfit2() {


		Retrofit retrofit = new Retrofit.Builder()//
				.baseUrl(Constant.URL_BASE)//
				.build();//

		MyServerInterface myServerInterface = retrofit.create(MyServerInterface.class);//建立一个http
		Call<ResponseBody> call = myServerInterface.getLastestJsonString();//添加泛型,获取回调内容
		call.enqueue(new Callback<ResponseBody>() {
			@Override
			public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

				//获取到响应
				if (response.isSuccessful()){

					try {
						String result = response.body().string();
						LogUtils.d("itchen-->成功内容-?" + result);
						textView_info.setText("itchen--result=" + result);
					} catch (IOException e) {
						e.printStackTrace();
					}

				}


			}

			@Override
			public void onFailure(Call<ResponseBody> call, Throwable t) {

			}
		});


	}

	private void initRetorfit() {

		//初始化数据之后定义一个retrofit
		Retrofit retrofit = new Retrofit.Builder()
				.baseUrl(Constant.URL_BASE).build();//链式写法

		//第二部将刚才定义的接口作为参数
		MyServerInterface myServerInterface = retrofit.create(MyServerInterface.class);
		retrofit2.Call<ResponseBody> call = myServerInterface.getLastestJsonString();//添加泛型.
		call.enqueue(new Callback<ResponseBody>() {
			@Override
			public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
				//String result = response.body().string();
				//如果服务器给的响应不为空,那么
				if (response.isSuccessful()) {
					try {
						String result = response.body().string();
						LogUtils.d("itchen-->成功内容-?" + result);
						textView_info.setText("itchen--result=" + result);
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}

			@Override
			public void onFailure(Call<ResponseBody> call, Throwable t) {

				LogUtils.d("itchen-->错误提示内容-->" + t.getMessage());

			}
		});

	}

	private void initView() {

		textView_info = (TextView) findViewById(R.id.textView_info);

	}

	@OnClick(R.id.buttonretrofit1)
	void ButtonTrofit() {


	}
}
